/**
 *	Handles click and mouse movement events, passing them back 
 *	to the display logic for handling
**/

"use strict"

var MouseEvents = {
	
	_debug: false,
	
	
	//(re)make the click events
	createMouseEvents: function(parent, game, localPlayer) {
		//add the movement events
		parent.onclick = function(e) {
			var xpos = Math.floor( e.layerX / (parent.offsetWidth / game.board.w) ),
				ypos = Math.floor( e.layerY / (parent.offsetHeight / game.board.h) )
			
			//anly allow local moves if it is not 'localPlayer's turn
			//		(unless debug mode is on, in which case allow all)
			if ( game.winner ) {
				//note: this functionality is duplicated due to logic flow
				var winner = ( game.winner == -1 ? "draw" : game.players[game.winner] )
				Game.GUI.userLog( "can't move, game already won by: " + winner )
			} else if ( MouseEvents._debug || game.turn === localPlayer.num ) {
				Game.makeMove(xpos, ypos)
			} else {
				Game.GUI.userLog( "please wait for remote player to take their turn" )
			}
		}
		
		//stop random DOM highlights occurring
		parent.onmousedown = function(e) {
			return false
		}
	},
	
	//temp location(?) - create timer events which check the server for a move
	createTimerEvents: function(game, localPlayer) {
		
		//function to run on interval
		var intervalFunc = function() {
			if (game.turn === localPlayer.num					//don't bother to run if it is your turn (just wasted resources)
				|| game.winner > 0)  return						//also ignore if game already won
			
			var moveRequest = { gameId: game.gameId }			//game to check for
			var callback = function(payload) {
				var move = JSON.parse(payload)
				if (move.turnCount > game.turnCount) {			//check if opponent has actually made a move yet
					Game.makeMove(move.x, move.y)							
				}
			}
			
			API.getMove( moveRequest, callback )				//get latest move from API
			console.log("checking for opponents move...")
		}
				
		//create the main interval event
		this._myinterval = setInterval(intervalFunc, 1000)		//run once per second
	}
	
}